package at.sysarch.filter;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.StreamCorruptedException;

import at.pimpmypipe.filter.AbstractSource;
import at.sysarch.model.Line;

public class Source extends AbstractSource<Line> {
	
	private BufferedReader _fileReader;
	private int _index;
	
	public Source() throws FileNotFoundException {
		
		initialize();
	}

	/**
	 * Reads from aliceInWonderland.txt
	 * Return one line per call.
	 */
	@Override
	public Line read() {

		try {
			
			String data = _fileReader.readLine();
			Line line = null;
			if (data != null) {
				
				line = new Line();
				
				line.setData(data);
				line.setIndex(_index);
				
				_index++;
			}

			return line;
		} 
		catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}

	@Override
	protected void beforeSendingEndingSignal() throws StreamCorruptedException {

		try {
			_fileReader.close();
		} catch (IOException e) {

			e.printStackTrace();
		}
	}
	
	/**
	 * Resets the FileReader.
	 * Must be called before the pipeline can be restarted.
	 * @throws FileNotFoundException
	 */
	public void initialize() throws FileNotFoundException {
		
		if (_fileReader != null) {
			
			try {
				_fileReader.close();
			} catch (IOException e) {

				e.printStackTrace();
			}
		}
		
		_fileReader = new BufferedReader(new FileReader("./Files/aliceInWonderland.txt"));
		_index = 0;
	}

}
